package com.yeehot.iot_manager;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import android.view.Window;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeehot.iot_manager.adapter.RefreshAdapter;
import com.yeehot.iot_manager.bean.Device;
import com.yeehot.iot_manager.ui.login.LoginActivity;
import com.yeehot.iot_manager.utils.INetCallBack;
import com.yeehot.iot_manager.utils.OkHttpUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    List<Device> mDatas = new ArrayList<>();
    private RefreshAdapter mRefreshAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    int page=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
        initRecylerView();

        initListener();

        handler.postDelayed(runnable, 2000);//每两秒执行一次runnable.
        getdata();
    }

    private void initView() {

        mSwipeRefreshLayout.setColorSchemeColors(Color.RED,Color.BLUE,Color.GREEN);

    }

    Handler handler=new Handler();
    Runnable runnable=new Runnable(){
        @Override
        public void run() {

            getmessage();
            handler.postDelayed(this, 2000);
        }
    };

    private void getmessage() {

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("consumerAccount",LoginActivity.userName);
        jsonObject.put("time", new Date().getTime());
        OkHttpUtils.getInstance().doPostJson("message", jsonObject.toJSONString(), new INetCallBack() {
            @Override
            public void onSuccess(String response) {
                mSwipeRefreshLayout.setRefreshing(false);
                JSONObject data=JSONObject.parseObject(response);
                System.out.println(response+"===");
                if (data.getBoolean("success"))
                {


                    JSONArray list=data.getJSONArray("data");

                    if (list!=null && list.size()>0) {
                        for (int i=0;i<list.size();i++){

                            Toast.makeText(MainActivity.this, list.getJSONObject(i).getString("content"), Toast.LENGTH_SHORT).show();
                        }
                    }

                }

            }

            @Override
            public void onFailed(Throwable ex) {
                mSwipeRefreshLayout.setRefreshing(false);
                Toast.makeText(MainActivity.this,"网络错误",Toast.LENGTH_LONG).show();
            }
        });

    }

    private void getdata() {

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("consumerAccount",LoginActivity.userName);
        jsonObject.put("page",page);
        jsonObject.put("limit",100);

        OkHttpUtils.getInstance().doPostJson("deviceList", jsonObject.toJSONString(), new INetCallBack() {
            @Override
            public void onSuccess(String response) {
                mSwipeRefreshLayout.setRefreshing(false);
                JSONObject data=JSONObject.parseObject(response);
                if (data.getBoolean("success"))
                {


                    JSONArray list=data.getJSONObject("data").getJSONArray("list");

                    if (list!=null)
                    {
                        for (int i=0;i<list.size();i++){


                            Device device=new Device();
                            device.setDeviceStatus(list.getJSONObject(i).getString("deviceStatus"));
                            device.setDeviceName(list.getJSONObject(i).getString("deviceName"));

                            mDatas.add(device);
                        }
                    }

                    mRefreshAdapter.AddHItem(mDatas);
                    //System.out.println(response+"===");
                }

            }

            @Override
            public void onFailed(Throwable ex) {
                mSwipeRefreshLayout.setRefreshing(false);
                Toast.makeText(MainActivity.this,"网络错误",Toast.LENGTH_LONG).show();
            }
        });

    }

    private void initRecylerView() {

        mRefreshAdapter = new RefreshAdapter(this);
        mLinearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);

        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(mRefreshAdapter);

    }

    private void initListener() {

        initPullRefresh();

        initLoadMoreListener();

    }



    private void initPullRefresh() {
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDatas.clear();;
                mRefreshAdapter.CleanData();
                page=1;
                System.out.println(page+"页数");
                 getdata();

            }
        });
    }

    private void initLoadMoreListener() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);



            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);


                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == mRefreshAdapter.getItemCount()) {


                    boolean isRefreshing = mSwipeRefreshLayout.isRefreshing();

                     page++;
                    getdata();
                }
            }
        });



    }
}